<template>
  <div class="app-container">
    <Pagetitle
      :title="pageTitle.title"
      :name="pageTitle.name"
      :btnName="pageTitle.btnName"
      @btnFun="btnFun"
    ></Pagetitle>
    <div class="filter-container">
      <Row>
        <Col :md="4">
        <DatePicker
          v-model="userHistoryDate"
          type="month"
          :clearable="false"
          format="yyyy-MM"
          placeholder="完成日期"
          @on-change="search"
        ></DatePicker>
        </Col>
        <Col
          :md="20"
          class="search-btn"
        >
        </Col>
      </Row>
    </div>
    <div class="brand-history">
      <Tabs
        v-model="searchForm.tabdepart"
        @on-click="getTabdepart()"
        :animated="false"
      >
        <TabPane
          v-for="(tab,index) in brandInfo.departmentList"
          :key="index"
          :label="tab.departmentName"
          :name="tab.departmentId.toString()"
          :value="tab.departmentId.toString()"
        >
          <div
            class="table-container"
            style="margin-top:0px;"
          >
            <div class="chart-title">
              成本中心-{{tab.departmentName}}
            </div>
            <easyChart
              :id="'brandChart'"
              :data='brandCostOption'
              :isShow='brandCostIsShow'
              v-if="searchForm.tabdepart === tab.departmentId.toString()"
            ></easyChart>
          </div>

          <div class="table-container">
            <div class="chart-title">
              物料<span class="chart-subtitle">（单位：数量）</span>
            </div>
            <easyChart
              :id="'brandMaterial'"
              :data='materialOption'
              :isShow='materialIsShow'
              v-if="searchForm.tabdepart === tab.departmentId.toString()"
            ></easyChart>
          </div>
          <div class="table-container">
            <div class="chart-title">
              员工-{{tab.departmentName}}
              <span class="chart-subtitle">（单位：分值）</span>
            </div>
            <easyChart
              :id="'brandStaff'"
              :data='staffOption'
              :isShow='staffIsShow'
              v-if="searchForm.tabdepart === tab.departmentId.toString()"
            ></easyChart>
          </div>
        </TabPane>
      </Tabs>

      <div class="table-container">
        <Table
          ref="brandHistroy"
          stripe
          :loading="dataTable.loading"
          :border="dataTable.border"
          :columns="dataTable.columns"
          :data="dataTable.data"
        ></Table>

        <Row class="mtop20">
          <Col
            :md="4"
            class="flex-start-center height-30 page"
          >
          <div>
            共{{count}}条
            <Select
              v-model="limit"
              size="small"
              class="lz-select-width"
              @on-change="changePageSize(1)"
            >
              <Option
                v-for="(item,index) in pageSizeSeletc"
                :value="item.value"
                :key="index"
              >{{ item.label }}</Option>
            </Select>
          </div>
          </Col>
          <Col
            :md="12"
            class="flex-center-center height-30"
          >
          <Page
            v-if="pageshow"
            :total="count"
            :page-size="limit"
            @on-change="changePageSize"
            size="small"
            show-elevator
          />
          </Col>
          <Col :md="8">
          <div class="page-size">
            <div
              class="keying-btn border-red"
              @click="downLoadExl()"
            >下载表格</div>
          </div>
          </Col>
        </Row>
      </div>
    </div>

  </div>
</template>
<script>
import { mapGetters } from "vuex";
import {
  fetchBrandHistory,
  fetchBrandMaterial,
  fetchBrandStaff,
  fetchBrandCostCent,
  fetchBrandHistoryDownload
} from "@/api/table";
import easyChart from "@/components/EasyChart";
import { Pagetitle, Model } from "@/components";
import format from "date-format";
import axios from "axios";
import fileDownload from "js-file-download";
import { getStore } from "@/utils/index";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      pageshow: true,
      //总页码
      count: 0,
      //页码
      currentPage: 1,
      //总条数
      limit: 10,
      pageSizeSeletc: [
        {
          value: 10,
          label: "10条/页"
        },
        {
          value: 20,
          label: "20条/页"
        }
      ],
      modal1: false,
      brandInfo: "",
      pageTitle: {
        title: "员工报表"
      },
      dataTable: {
        loading: false,
        border: false,
        columns: [
          {
            minWidth: 100,
            title: "品牌",
            key: "brandName"
          },
          {
            minWidth: 100,
            title: "部门",
            key: "departmentName"
          },
          {
            minWidth: 120,
            title: "完成时间",
            key: "materialCount",
            render: (h, params) => {
              return h(
                "div",
                format("yyyy-MM", new Date(params.row.finishTime))
              );
            }
          },
          {
            minWidth: 100,
            title: "总分值",
            key: "totalScore"
          }
        ],
        data: []
      },
      timeSelectValue: "1",
      timeSelect: [
        {
          value: "1",
          label: "按月份"
        }
      ],
      userHistoryDate: "",
      dateType: "month",
      searchForm: {
        startTime: "",
        endTime: "",
        tabdepart: ""
      },
      materialIsShow: false,
      materialOption: {},
      materialData: {
        name: [],
        count: []
      },
      staffIsShow: false,
      staffOption: {},
      brandStaffData: {
        name: [],
        count: []
      },
      brandCostIsShow: true,
      brandCostOption: {},
      brandCostData: []
    };
  },
  components: {
    Pagetitle,
    Model,
    easyChart
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.brandInfo = JSON.parse(getStore("brandInfo"));
      this.pageTitle.title = "品牌报表>" + this.brandInfo.brandName;
      this.userHistoryDate =
        this.$route.query.time || format("yyyy-MM", new Date());
      if (this.brandInfo.departmentList[0].departmentId) {
        this.searchForm.tabdepart = this.brandInfo.departmentList[0].departmentId.toString();
      }
      this.getbrandHistory();
    },
    //分页
    changePageSize(index) {
      this.currentPage = index;
      this.getbrandHistory();
    },
    search() {
      this.currentPage = 1;
      this.pageshow = false;
      this.getbrandHistory();
      this.$nextTick(() => {
        this.pageshow = true;
      });
    },
    getTabdepart() {
      this.getbrandHistory();
    },
    async getbrandHistory() {
      let start;
      let end;
      if (this.userHistoryDate !== "") {
        const nowDate = format("yyyy-MM", new Date(this.userHistoryDate));
        if (this.timeSelectValue === "3") {
          start = nowDate[0];
          end = nowDate[1];
        } else if (this.timeSelectValue === "2") {
          start = nowDate + "-01-01";
          end = nowDate + "-12-31";
        } else if (this.timeSelectValue === "1") {
          const spData = nowDate.split("-");
          start = nowDate + "-01";
          end = nowDate + "-" + this.mGetDate(spData[0], spData[1]);
        }
      }

      this.dataTable.loading = true;
      const res = await fetchBrandHistory({
        pageNo: this.currentPage,
        pageSize: this.limit,
        startTime: start,
        endTime: end,
        departmentId: this.searchForm.tabdepart,
        brandId: this.brandInfo.brandId
      });
      const brandStaff = await fetchBrandStaff({
        startTime: start,
        endTime: end,
        departmentId: this.searchForm.tabdepart,
        brandId: this.brandInfo.brandId
      });
      const brandMaterial = await fetchBrandMaterial({
        startTime: start,
        endTime: end,
        departmentId: this.searchForm.tabdepart,
        brandId: this.brandInfo.brandId
      });
      const brandCost = await fetchBrandCostCent({
        startTime: start,
        endTime: end,
        departmentId: this.searchForm.tabdepart,
        brandId: this.brandInfo.brandId
      });
      this.materialData.name = [];
      this.materialData.count = [];
      if (brandMaterial.data.length > 0) {
        brandMaterial.data.forEach(item => {
          this.materialData.name.push(item.materialName);
          this.materialData.count.push(item.brandMaterialCount);
        });
      }
      this.brandStaffData.name = [];
      this.brandStaffData.count = [];
      if (brandStaff.data.length > 0) {
        brandStaff.data.forEach(item => {
          this.brandStaffData.name.push(item.name);
          this.brandStaffData.count.push(item.userBrandScoreCount);
        });
      }
      this.brandCostData = [];
      if (brandCost.data.length > 0) {
        brandCost.data.forEach(item => {
          const staffData = {};
          staffData.name = item.costCentName;
          staffData.value = item.costCentScore;
          this.brandCostData.push(staffData);
        });
      }
      this.setBrandMaterialOption();
      this.setBrandCostOption();
      this.setBrandStaffOption();
      this.dataTable.loading = false;
      this.count = res.data.total;
      this.dataTable.data = [];
      this.dataTable.columns = [
        {
          minWidth: 100,
          title: "品牌",
          key: "brandName"
        },
        {
          minWidth: 100,
          title: "部门",
          key: "departmentName"
        },
        {
          minWidth: 120,
          title: "完成时间",
          key: "materialCount",
          render: (h, params) => {
            return h("div", format("yyyy-MM", new Date(params.row.finishTime)));
          }
        },
        {
          minWidth: 100,
          title: "总分值",
          key: "totalScore"
        }
      ];
      if (res.data.list.length > 0) {
        res.data.columns.forEach(item => {
          const columns = {};
          columns.minWidth = 100;
          columns.key = item;
          columns.title = item;
          this.dataTable.columns.splice(3, 0, columns);
        });
        for (var i = 0, l = res.data.list.length; i < l; i++) {
          const data = {};
          for (var key in res.data.list[i]) {
            data[key] = res.data.list[i][key];
          }
          this.dataTable.data.push(data);
        }
      }
    },
    btnFun() {},
    downLoadExl() {
      const href =
        process.env.BASE_URL +
        "statement/brandHistoryDownload?departmentId=" +
        this.searchForm.tabdepart +
        "&brandId=" +
        this.brandInfo.brandId;
      window.open(href, "_blank");
    },
    // async downLoadExl() {
    //   const res = await fetchBrandHistoryDownload({
    //     departmentId: this.searchForm.tabdepart,
    //     brandId: this.brandInfo.brandId
    //   });
    // },
    //获得月天数
    mGetDate(year, month) {
      var d = new Date(year, month, 0);
      return d.getDate();
    },
    setBrandCostOption() {
      // this.brandCostIsShow = false;
      // if (this.brandCostData.length > 0) {
      //   // this.brandCostIsShow = true;
      this.brandCostOption = {
        grid: {
          top: 800
        },
        series: [
          {
            name: "品牌",
            type: "pie",
            radius: "25%",
            radius: ["50%", "60%"],
            avoidLabelOverlap: true,
            animation: false,
            labelLine: {
              //图形外文字线
              normal: {
                lineStyle: {
                  color: "#222121"
                },
                length: 35,
                length2: 150
              }
            },
            label: {
              position: "outer",
              alignTo: "labelLine",
              color: "#222121",
              formatter: "{b}: {d}%\n\n",
              padding: [0, -120], //在线上
              bleedMargin: 5
            },
            itemStyle: {
              normal: {
                color: function(params) {
                  //自定义颜色
                  var colorList = [
                    "#CB2D00",
                    "#1B6EC1",
                    "#2F86DC",
                    "#96CAFF",
                    "#FFD7CC",
                    "#FFAD96",
                    "#F98D6E",
                    "#EF6A44",
                    "#E4572F"
                  ];
                  return colorList[params.dataIndex];
                }
              }
            },
            data: this.brandCostData
          }
        ]
      };
      // } else {
      //   this.brandCostOption = {
      //     title: {
      //       text: "暂无数据"
      //     }
      //   };
      // }
    },
    setBrandMaterialOption() {
      // this.materialIsShow = false;
      // if (this.materialData.count.length > 0) {
      //   this.materialIsShow = true;
      this.materialOption = {
        grid: {
          bottom: 80
        },
        xAxis: {
          type: "category",
          data: this.materialData.name,
          axisLine: {
            //x轴
            show: false
          },
          axisTick: {
            //x轴刻度线
            show: false
          },
          splitLine: {
            //网格线
            show: false
          },
          axisLabel: {
            interval: "auto",
            rotate: "45",
            fontSize: 10
          }
        },
        yAxis: [
          {
            show: false,
            axisLine: {
              //x轴
              show: false
            },
            axisTick: {
              //x轴刻度线
              show: false
            },
            splitLine: {
              //网格线
              show: false
            }
          }
        ],
        series: [
          {
            data: this.materialData.count,
            type: "bar",
            barMaxWidth: 12,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#5B5959"
              }
            }
          }
        ]
      };
      // } else {
      //   this.materialOption = {};
      //   this.materialIsShow = false;
      // }
    },
    setBrandStaffOption() {
      //   this.staffIsShow = false;
      //   if (this.brandStaffData.count.length > 0) {
      //     this.staffIsShow = true;
      this.staffOption = {
        grid: {
          bottom: 80
        },
        xAxis: {
          type: "category",
          data: this.brandStaffData.name,
          axisLine: {
            //x轴
            show: false
          },
          axisTick: {
            //x轴刻度线
            show: false
          },
          splitLine: {
            //网格线
            show: false
          },
          axisLabel: {
            interval: "auto",
            rotate: "45",
            fontSize: 10
          }
        },
        yAxis: [
          {
            show: false,
            axisLine: {
              //x轴
              show: false
            },
            axisTick: {
              //x轴刻度线
              show: false
            },
            splitLine: {
              //网格线
              show: false
            }
          }
        ],
        series: [
          {
            data: this.brandStaffData.count,
            type: "bar",
            barMaxWidth: 12,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#5B5959"
              }
            }
          }
        ]
      };
      //   } else {
      //     this.staffOption = {};
      //     this.staffIsShow = false;
      //   }
    }
  },
  computed: {
    ...mapGetters(["userId", "rolesId"]),
    downLoad: () => {
      return process.env.BASE_URL;
    }
  }
};
</script>
<style lang="less" scoped>
@import "~@/styles/mixin";
.brand-history {
  margin-top: 10px;
}
.clear-search {
  margin-left: 10px;
}
.group-user {
  color: @default-color;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  font-weight: 500;
}
.warning {
  margin-left: 30px;
  color: @primary-color;
}
.total-score {
  font-size: 16px;
  color: @default-color;
  margin-bottom: 20px;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  span {
    color: @primary-color;
  }
}
.filter-container {
  border-radius: 8px;
  margin-top: 15px;
  background-color: #fff;
  padding: 20px;
}
.date-picker {
  width: 208px;
  line-height: 30px;
  margin-left: 10px;
}
.search-btn {
  display: flex;
  justify-content: flex-end;
}
</style>
<style>
.brand-history .ivu-tabs-nav-container:focus {
  outline: none;
}
.brand-history .ivu-tabs-ink-bar {
  height: 0;
}
.brand-history .ivu-tabs-bar {
  margin-bottom: 0;
}
.brand-history .ivu-tabs-nav .ivu-tabs-tab {
  margin-right: 0;
  padding: 0 20px 10px 0;
}
</style>